package top.kaoshanji.r3ch11b;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 代码清单-r3ch11b-377页a：采用编程式的事务管理
 * @author kaoshanji
 * ^_^
 * create time 2025/5/9 13:41
 */
@Service
public class ForumTxProgrammingService {

    private ForumDao forumDao;
    private TransactionTemplate template;

    @Autowired
    public void setForumDao(ForumDao forumDao) {
        this.forumDao = forumDao;
    }

    // 通过AOP主动注入
    @Autowired
    public void setTemplate(TransactionTemplate template) {
        this.template = template;
    }

    public void addForum(final Forum forum) {

        // 编程式事务API
        template.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                // 需要在事务环境中执行的代码...
                forumDao.addForum(forum);
            }
        });

    }

}
